#'''
#Author: GY_books 2567610535@qq.com
#Date: 2023-12-22 16:14:08
#LastEditTime: 2024-12-25 19:32:40
#LastEditors: GY_books 2567610535@qq.com
#FilePath: \my-flask-api\views\user\user.py
#描述: 头部注释配置模板
#'''
# -*- coding:utf-8 -*-
from flask import Blueprint,g,request
from config import *
from base.utils import *
# from framework import my_jwt 
from flask_jwt_extended import create_access_token,get_jwt_identity,jwt_required
from framework.response_code import *

app_user = Blueprint('user',__name__,url_prefix='/user')


#登录
@app_user.route('/login', methods=['POST','GET'])
def login():
    data = request.get_json()
    name = data['name']
    password = data['password']
    print(name,password,'TTTTTTTTTTTT')
    if(name) & (password):
        sql = f'SELECT name,password,id FROM user WHERE name="{name}"'
        res = g.db.find(sql)
        g.db.close()
        if res:
            if verify_password(password,res['password']):
                return write_json( {'name':res['name'],'token':create_access_token(identity=res['id'])}),200
            return '账号/密码有误',201
        return '账号/密码有误',201
    return '账号/密码有误',201
        
#账号注册
@app_user.route('/register',methods=['POST','GET'])
def user_register():
    name = request.args.get('name')
    password = request.args.get('password')
    if (name != None) & (password != None):
        sql = f'SELECT name FROM user WHERE name="{name}"'
        # 查询用户名是否存在
        res = g.db.find(sql)
        if res == None:
            if (name != None) & (password != None):
                sql1 = f'INSERT INTO user (name,password) VALUES ("{name}","{encryp_password(password).decode("utf-8")}")'
                res1 = g.db.update(sql1)
                g.db.close()
                if res1:
                    return '注册成功',200
                return '账号/密码 不规范',202
            return '账号/密码有误',201
        return  '账号已存在',203
    return '账号/密码有误',201
    

#用户数据
@app_user.route('/info', methods=['GET'])
@jwt_required(locations=["headers"])
def userinfo():
    id = get_jwt_identity()
    if id:
        sql_str = f'SELECT name,id,nick_name,tel,avatar FROM user WHERE id="{id}"'
        res = g.db.find(sql_str)
        if not res:
            return '服务器内部错误，请稍后再试',500
        g.db.close()
        return write_json(res),200
    # if not id:
    #     return  {'code':201,'msg':''}
    # return {'code':200,'msg':'ok'}

# @app_user.route('/xg',methods=['GET'])
# def xg():
#     p = request.args.get('p')
#     sql_str = f'UPDATE user SET password="{encryp_password(p).decode("utf-8")}"'
#     res = g.db.update(sql_str)
#     g.db.close()
#         # print(res)
#     if not res:
#         return SERVICE_ERROR
#     return {'code':200,'data':res}



